<?php

namespace App\Http\Middleware;

use App\Personal\jwt;
use Closure;
use Illuminate\Http\Request;
use function App\Helpers\errorMsg;

class CheckTokenAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $jwt = new jwt();
        $res = $jwt->parse_toekn($request);//检测token是否为空
        if(is_array($res)) return response(errorMsg($res[0],$res[1]));
        $res = $jwt->check_sign();//检测token是否正确
        if(is_array($res)) return response(errorMsg($res[0],$res[1]));
        $res = $jwt->check();//检测token是否过期
        if(is_array($res)) return response(errorMsg($res[0],$res[1]));
        if($jwt->body_arr->aud != 'manage') return response(errorMsg(-1,"token 验证失败!!"));
        // 将id挂载到request中
        $request->merge(['manage_id' => $jwt->body_arr->sub]);
        return $next($request);
    }
}
